﻿using NetDh.Lib.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace NetDh.Lib
{
    /// <summary>
    /// 字符串Ticket和对象UserToken之间的转换
    /// </summary>
    public class TokenHelper
    {
        public static readonly string TOKEN_NAME = "_user_token_";
        /// <summary>
        /// Ticket中包含的属性个数
        /// </summary>
        public static readonly int PropertiesCount = 5;
        /// <summary>
        /// UserToken转为ticket
        /// </summary>
        public static string GetUserTicket(UserToken token, bool needUrlEncode = true)
        {
            //UserName不可修改而且频繁使用，则可加入ticket中，如果可修改则不加进来。一般昵称NickName是用户可修改。
            var result = $"{token.UserId}|{token.UserName}|{token.UserType}|{token.Platform}|{token.CreateTime.ToStringX()}";
            //result = AuthcodeX.Encode(result);
            result = SecurityUtil.EncryptAES(result);//todo 给DecryptAES加个变种。 此加密的字符串结果比较短，可自己增加创建时间，后继可验证token是否过期
            if (needUrlEncode)
            {
                result = HttpUtility.UrlEncode(result);
            }
            return result;
        }

        /// <summary>
        /// 获取用户Token信息
        /// </summary>
        public static UserToken GetToken(string ticket, bool needUrlDecode = true)
        {
            if (string.IsNullOrEmpty(ticket))
            {
                return null;
            }
            try
            {
                if (needUrlDecode)
                {
                    ticket = HttpUtility.UrlDecode(ticket);
                }
                //var arr = AuthcodeX.Decode(ticket).Split('|');
                var arr = SecurityUtil.DecryptAES(ticket).Split('|');
                if (arr.Length != PropertiesCount) return null;
                return new UserToken() { UserId = arr[0], UserName = arr[1], UserType = arr[2], Platform = arr[3], CreateTime = DateTime.Parse(arr[4]) };
            }
            catch (Exception ex)
            {
                MemoryLog.Add($"GetToken error.illegal ticket:{ticket}", MemoryLogType.illegal);
                return null;
            }
           
        }
    }
}
